package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.History;
import com.example.service.ArticalService;
import com.example.service.HistoryService;
import com.example.util.BeanFactroy;
import com.example.util.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/history/*")
public class HistoryController extends HttpServlet {
    private HistoryService historyService = BeanFactroy.createBean(HistoryService.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();

        if ("/addHistory".equals(path)) {
            addHistory(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();
        //测试
//        if ("/addHistory".equals(path)) {
//            addHistory(request, response);
//        }
    }

    private void addHistory(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Long userId = Long.parseLong(request.getParameter("userId"));
        Long typeId = Long.parseLong(request.getParameter("typeId"));
        int type = Integer.parseInt(request.getParameter("type"));
        //先查后加
        History history1 = historyService.isHistory(userId, typeId, type);
        //System.out.println(history1);

        if(history1 != null){
            //有记录,更新时间
            int i = historyService.updateTime(userId, typeId, type);
            response.getWriter().print(JSON.toJSONString(R.ok().data("updateTime",i)));
        }else{
        //为空
            History history = new History();
            history.setUserId(userId);
            history.setTypeId(typeId);
            history.setType(type);
            boolean flag = historyService.addHistory(history);
            if(flag){
                response.getWriter().print(JSON.toJSONString(R.ok()));
            }else{
//                System.out.println("flag:"+flag);
                response.getWriter().print(JSON.toJSONString(R.error()));
            }
        }




    }


}
